package com.xyhy.starter.mfx.codegen.dialect;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.codegen.dialect.AbstractJdbcDialect;
import com.mybatisflex.codegen.entity.Table;

import java.sql.*;
import java.util.Optional;

public class MssqlDialect extends AbstractJdbcDialect {

  @Override
  protected String forBuildColumnsSql(String schema, String tableName) {
    return "SELECT * FROM " + (StrUtil.isNotBlank(schema) ? schema + "." : "") + tableName + " WHERE 1 = 2";
  }

  @Override
  protected ResultSet forRemarks(String schemaName, Table table, DatabaseMetaData dbMeta, Connection conn) throws SQLException {
    String sql = "SELECT A.name AS table_name, B.name AS COLUMN_NAME, convert(varchar(200), C.value) AS REMARKS " +
            "FROM sys.tables AS A " +
            "INNER JOIN sys.schemas AS S on A.schema_id = S.schema_id " +
            "INNER JOIN sys.columns AS B ON B.object_id = A.object_id " +
            "LEFT OUTER JOIN sys.extended_properties AS C ON C.major_id = B.object_id AND C.minor_id = B.column_id " +
            "WHERE S.name = ? AND A.name = ? order by B.name";

    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setString(1, Optional.ofNullable(schemaName).orElse("dbo"));
    ps.setString(2, table.getName());

    return ps.executeQuery();
  }

  @Override
  public ResultSet getTablesResultSet(DatabaseMetaData dbMeta, Connection conn, String schema, String[] types) throws SQLException {
    String sql = "SELECT TOP 10000 ROW_NUMBER() OVER (ORDER BY A.name) AS No, A.name AS TABLE_NAME, " +
            "   CONVERT(NVARCHAR(100),isnull(g.[value],'-')) AS REMARKS " +
            "FROM sys.tables A " +
            "INNER JOIN sys.schemas AS S on A.schema_id = S.schema_id " +
            "LEFT JOIN sys.extended_properties g on (a.object_id = g.major_id AND g.minor_id = 0) " +
            "WHERE S.name = ?";

    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setString(1, Optional.ofNullable(schema).orElse("dbo"));

    return ps.executeQuery();
  }
}
